package com.okq.action;

import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Company;
import com.okq.entity.Group;
import com.okq.entity.Role;
import com.okq.entity.User;
import com.okq.service.*;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述 : 部门action
 * 作者 : zdl
 * 日期 : 2017/6/28 10:58
 */
public class GroupAction extends BaseActionSupport {

    private static final long serialVersionUID = 4772646641968249641L;

    /**
     * 公司接口
     */
    @Autowired
    private ICompanyService companyServiceImpl;
    /**
     * 部门接口
     */
    @Autowired
    private IGroupService groupServiceImpl;
    /**
     * 角色接口
     */
    @Autowired
    private IRoleService roleServiceImpl;
    /**
     * 人员接口
     */
    @Autowired
    private IUserService userServiceImpl;
    /**
     * 系统日志接口
     */
    @Autowired
    private ILogService logServiceImpl;
    /**
     * 日志
     */
    private static final Logger logger = Logger.getLogger(GroupAction.class);

    /**
     * 分页开始条数
     */
    private int iDisplayStart;

    /**
     * 每页显示条数
     */
    private int iDisplayLength;

    private Group group;
    private String id;
    private String groupName;
    private String companyId;// 公司ID
    /**
     * 操作类型
     */
    private String type;

    /**
     * 获取部门列表
     *
     * @return json
     */
    public String getGroupList() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                if (iDisplayLength == 0) {
                    iDisplayLength = -1;
                }
                int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
                /* 分页信息 */
                Page<Group> pageInfo = new Page<>(iDisplayLength);
                pageInfo.setPageNo(pageNum);

                pageInfo = groupServiceImpl.pageByGroup(pageInfo, group);
                int iTotalRecords = pageInfo.getTotalCount();
                int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();
                /* 得到结果 */
                List<Group> gList = pageInfo.getResult();
                /* 封装list */
                List<Map<String, Object>> groupMapList = new ArrayList<>();
                if (gList != null && !gList.isEmpty() && gList.size() > 0) {
                    int i = (pageNum - 1) * iDisplayLength + 1;
                    for (Group g : gList) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("no", i);// 序号
                        map.put("id", g.getId());
                        map.put("groupName", StringUtils.defaultString(g.getGroupName(), ""));
                        String comName = "";
                        String companyId = g.getCompanyId();
                        if (StringUtils.isNotBlank(companyId)) {
                            Company com = companyServiceImpl.getCompanyById(companyId);
                            if (com != null) {
                                comName = StringUtils.defaultString(com.getName(), "");
                            }
                        }
                        map.put("comName", comName);
                        map.put("remark", StringUtils.defaultString(g.getRemark(), ""));
                        map.put("createUser", StringUtils.defaultString(g.getCreateUserName(), ""));
                        map.put("createTime", TimeTool.timestampToString(g.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
                        groupMapList.add(map);
                        i++;
                    }
                }
                Map<String, Object> jsonMap = new HashMap<>();
                jsonMap.put("iTotalRecords", iTotalRecords);
                jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
                jsonMap.put("aaData", groupMapList);

                String json = BaseTool.toJson(jsonMap);
                out.print(json);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 删除
     *
     * @return 是否成功标识
     */
    public String deleteGroup() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                List<User> uList = userServiceImpl.listUserByGroupId(id);
                if (uList != null && !uList.isEmpty() && uList.size() > 0) {
                    out.print(1);
                    return null;
                } else {
                    Group g = groupServiceImpl.getGroupById(id);
                    if (g != null) {
                        // 修改删除状态为1
                        g.setIsDelete(1);
                        g.setUpdateUserId(loginUser.getId());
                        g.setUpdateUserName(loginUser.getUserName());
                        groupServiceImpl.updateGroup(g);
                        out.print(0);
                        //添加系统日志
                        String userName = loginUser.getUserName();
                        String nowTime = TimeTool.getNowTime();
                        String comName = getComNameById(g.getCompanyId());
                        String content = "用户：" + userName + "，于" + nowTime + " 删除“" + comName + "”下属部门：" + g.getGroupName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "部门管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 跳转到修改页面
     *
     * @return success
     */
    @SuppressWarnings("all")
    public String toUpdatePage() {
        try {
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && StringUtils.isNotBlank(id)) {
                group = groupServiceImpl.getGroupById(id);
                if (group != null) {
                    return SUCCESS;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
        return null;
    }

    /**
     * 保存
     *
     * @return 是否成功标识
     */
    public String saveGroup() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null && group != null) {
                Company com = companyServiceImpl.getCompanyById(group.getCompanyId());
                if (com == null) {
                    out.print("noexist");
                    return null;
                }
                if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
                    Group g = groupServiceImpl.getGroupByName(group.getGroupName(), group.getCompanyId());
                    if (g != null) {
                        out.print("exist");
                        return null;
                    } else {
                        group.setId(BaseTool.getPK());
                        group.setComCode(com.getComCode());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            group.setCreateUserId(loginUser.getId());
                            group.setCreateUserName(userName);
                        }
                        groupServiceImpl.saveGroup(group);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String comName = getComNameById(group.getCompanyId());
                        String content = "用户：" + userName + "，于" + nowTime + " 新增“" + comName + "”下属部门：" + group.getGroupName() + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "部门管理", 2, content, logServiceImpl);
                    }
                } else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
                    String newName = group.getGroupName();
                    String newComId = group.getCompanyId();
                    Group gro = groupServiceImpl.getGroupById(group.getId());
                    if (gro != null) {
                        String oldName = gro.getGroupName();
                        String oldComId = gro.getCompanyId();
                        Group g = null;
                        if (StringUtils.isNotBlank(newName) && StringUtils.isNotBlank(oldName) && StringUtils.isNotBlank(newComId)
                                && StringUtils.isNotBlank(oldComId) && !newName.equals(oldName) && !newComId.equals(oldComId)) {
                            g = groupServiceImpl.getGroupByName(newName, newComId);
                        } else if (StringUtils.isNotBlank(newName) && StringUtils.isNotBlank(oldName) && !newName.equals(oldName)) {
                            g = groupServiceImpl.getGroupByName(newName, oldComId);
                        } else if (StringUtils.isNotBlank(newComId) && StringUtils.isNotBlank(oldComId) && !newComId.equals(oldComId)) {
                            g = groupServiceImpl.getGroupByName(oldName, newComId);
                        }
                        if (g != null) {
                            out.print("exist");
                            return null;
                        }
                        gro.setGroupName(newName);
                        gro.setCompanyId(newComId);
                        gro.setRemark(group.getRemark());
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            gro.setUpdateUserId(loginUser.getId());
                            gro.setUpdateUserName(userName);
                        }
                        groupServiceImpl.updateGroup(gro);
                        out.print("success");
                        //添加系统日志
                        String nowTime = TimeTool.getNowTime();
                        String comName = getComNameById(group.getCompanyId());
                        String content = "用户：" + userName + "，于" + nowTime + " 修改“" + comName + "”下属部门：" + newName + "！";
                        PublicClass.addLog(userName, loginUser.getLoginName(), "部门管理", 2, content, logServiceImpl);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 获取公司下的全部部门
     *
     * @return json
     */
    public String getAllGroup() {
        PrintWriter out = null;
        try {
            out = this.getResponse().getWriter();
            User loginUser = (User) getSession().getAttribute("loginUser");
            if (loginUser != null) {
                List<Group> gList = new ArrayList<>();
                String roleId = loginUser.getRoleId();
                if (StringUtils.isNotBlank(roleId)) {
                    Role role = roleServiceImpl.getRoleById(roleId);
                    if (role != null) {
                        Integer roleType = role.getRoleType();
                        if (roleType == 0 || roleType == 1) {// 管理员和超级管理员查询公司下所有部门
                            gList = groupServiceImpl.listGroupByComId(companyId);
                        } else {
                            String loginGroupId = loginUser.getGroupId();
                            if (StringUtils.isNotBlank(loginGroupId)) {
                                Group group = groupServiceImpl.getGroupById(loginGroupId);
                                if (group != null) {
                                    gList.add(group);
                                }
                            }
                        }
                    }
                }
                String data = BaseTool.toJson(gList);
                out.print(data);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

    /**
     * 根据公司Id获取公司名称
     *
     * @param companyId 公司Id
     * @return 公司名称
     */
    private String getComNameById(String companyId) {
        String comName = "";
        if (StringUtils.isNotBlank(companyId)) {
            Company c = companyServiceImpl.getCompanyById(companyId);
            if (c != null) {
                comName = StringUtils.defaultString(c.getName(), "");
            }
        }
        return comName;
    }

    public int getIDisplayStart() {
        return iDisplayStart;
    }

    public void setIDisplayStart(int iDisplayStart) {
        this.iDisplayStart = iDisplayStart;
    }

    public int getIDisplayLength() {
        return iDisplayLength;
    }

    public void setIDisplayLength(int iDisplayLength) {
        this.iDisplayLength = iDisplayLength;
    }

    public Group getGroup() {
        return group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public String getCompanyId() {
        return companyId;
    }

    public void setCompanyId(String companyId) {
        this.companyId = companyId;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}
